#!/usr/bin/python3

# Copyright (c) 2020-2021 Fpemud <fpemud@sina.com>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.


from .util import Util, MachineIdFile
from .errors import ConfigError
from .const import MachineType
from .handy import MachineInfoFile, MachineHwcfgFile
from .prototypes import Vendor
from .snapshot import SysSnapshot
from .vendor import VendorUtil


def get_all_vendors():
    ret = []
    for vendorName in VendorUtil.getVendorNames():
        ret.append(Vendor(VendorUtil.getVendorImpl(vendorName)))
    return ret


def get_vendor(vendor_id):
    return Vendor(VendorUtil.getVendorImpl(vendor_id))


def init_machine_branded(vendor, model, serial, machine_id):
    assert vendor in VendorUtil.getVendorNames()
    assert model is not None

    if not MachineIdFile.check():
        if machine_id == "random":
            MachineIdFile.generate()
        else:
            MachineIdFile.save(machine_id)

    MachineInfoFile.saveMachineInfo({
        "HARDWARE_VENDOR": vendor,
        "HARDWARE_MODEL": model,
        "CHASSIS": None,
    })

    if serial is not None:
        bChanged = MachineHwcfgFile.catProperties().machine_add_apply_serial(serial)
    else:
        bChanged = MachineHwcfgFile.catProperties().machine_remove_apply_serial()
    if bChanged:
        MachineHwcfgFile.save()


def init_machine_assembled(machine_type, machine_id):
    assert isinstance(machine_type, MachineType)

    if not MachineIdFile.check():
        if machine_id == "random":
            MachineIdFile.generate()
        else:
            MachineIdFile.save(machine_id)

    MachineInfoFile.saveMachineInfo({
        "HARDWARE_VENDOR": None,
        "HARDWARE_MODEL": None,
    })

    MachineInfoFile.saveChassisType(machine_type)

    if MachineHwcfgFile.catProperties().machine_remove_apply_serial():
        MachineHwcfgFile.save()


def update_machine():
    mObj = probe()
    if MachineHwcfgFile.catSaved().flush(mObj):
        MachineHwcfgFile.save()


def reset_machine():
    Util.forceDelete(MachineIdFile.PATH)
    Util.forceDelete(MachineInfoFile.PATH)
    Util.forceDelete(MachineHwcfgFile.PATH)


def probe():
    machineInfoDict = MachineInfoFile.getMachineInfo()
    sysSnapshot = SysSnapshot()

    # get machine object
    mObj = None
    if True:
        # use vendor and model in /etc/machine-info
        vendor = machineInfoDict.get("HARDWARE_VENDOR", None)
        model = machineInfoDict.get("HARDWARE_MODEL", None)
        if vendor is not None:
            if model is None:
                raise ConfigError("HARDWARE_VENDOR property is present but HARDWARE_MODEL property is missing in %s" % (MachineInfoFile.PATH))
            mObj = VendorUtil.getVendorImpl(vendor).probe_machine(sysSnapshot, model=model)
        else:
            if model is not None:
                raise ConfigError("HARDWARE_MODEL property is present but HARDWARE_VENDOR property is missing in %s" % (MachineInfoFile.PATH))
            # try each vendor one by one, fallback to "unknown" vendor
            for vendorName in VendorUtil.getVendorNames() + ["unknown"]:
                mObj = VendorUtil.getVendorImpl(vendorName).probe_machine(sysSnapshot)
                if mObj is not None:
                    break
            assert mObj is not None

    # saved components and dumb components should be exhausted
    if len(sysSnapshot.saved.query_components()) > 0:
        raise ConfigError("redundant saved component exists")
    if len(sysSnapshot.dumb.query_components()) > 0:
        raise ConfigError("redundant dumb component exists")

    # finish initialization
    mObj._makeReady()
    return mObj
